#!/usr/bin/perl # for syntax highlighting

sub mm_grant_portal_access($$;$) {
my ($portal,$user,$by)=@_;

	my $url_prefix=$::GRI_FRONTEND->get_url_prefix();
	my $v=get_cookie_value(name=>"gri_dbm_intranet");
	$v=~ s/\s+.*//;
	if($v eq "public") {
		print STDERR "mm_send_email: User logged in as public - no email sent!\n";
		return "Unable to send mail - user logged in as 'public'";
	}

	my $p2=hex_to_string($portal); my $u2=hex_to_string($user);
	# We get the currenet list of users with access to the portal
	my $current_users=$::GRI_FRONTEND->get_portal_users($p2);

	# Check to see if the 
	if(! grep {$_ eq $u2} @$current_users) {
		push @$current_users,$u2;
		my ($rc,$e)=$::GRI_FRONTEND->set_portal_users($p2,join(",",@$current_users));
		if($rc==0) {
			my $serror="Error Changing Portal User Access";
			my $error=$e;

			my $link="$url_prefix$::ENV{SCRIPT_NAME}/show_generic_error?serror=".string_to_hex($serror).",error=".string_to_hex($error);
			if(!exists($::PARAM{lp})) {
				# We need to encode the current data for repopulation into the form!
				my $s="";
				$s.="portal=$portal";
				# $s.="::portal_filename=".string_to_hex($portal_filename);
				# $s.="::portal_users=".string_to_hex($portal_users);
				# $s.="::portal_template=".string_to_hex($portal_template);
				$link.=",previouspage=form_user_access_to_portal::$s";
			}
			redirect_header(path => $link);
			exit;
		}
	}

	#####################################################################
	# If we have granted access we also send the user an email			#
	# automatically indicating that we've granted them access.			#
	#####################################################################
	{
		my $admin_email;
		my $admin_email_txt;
		if(defined($by)) {
			$admin_email=$::GRI_FRONTEND->get_user_email_address($by->[1]);
			$admin_email=$by->[1] if !length($admin_email);
			$admin_email_txt="$by->[0] $admin_email";
		} else {
			$admin_email=$::GRI_FRONTEND->get_email_address("access_requests");
			$admin_email_txt=$admin_email;
		}
		my $email=$::GRI_FRONTEND->get_user_email_address($u2);
		if($email && $admin_email) {
			chomp $email;
			$::GRI_FRONTEND->send_email({
				html=>1,to=>$email,
				subject=>"Request access to portal '$p2' - Granted!",cc=>$admin_email,
				content=>"Your access request specified above has been granted by $admin_email_txt.\n"
			});
		}
		if(! $email) {
			return "Failed to send message - unable to resolve name '$v' to email address.";
		}
	}
	# Give a message indicating access has been granted...
	my $s="Access for user '$u2' has been granted. Click <a class=stdlink href=\"javascript:window.close();\">here</a> to close window.";
	return $s;
}

1;

# vim: ts=4:sw=4
